import { getMenuData, getMerchantsData } from '@/services/menu';
import { Reducer } from 'redux';
import { Effect } from 'dva';
import { getIcon } from "@/support/config/MenuIconConfig"
import { privateKey } from '../../public/global';
import { decryptedData } from '@/utils/utils';

export interface MenuModelState {
  menuData: any[];
  dicData: any[];
  permissions: any[],
  userProfile: any;
  pwdStrategy: any;
  basicData: any;
  orgType: any;
  dataPermission: any;
  merchantsData: any;
}
export interface MenuModelType {
  namespace: 'menu';
  state: MenuModelState;
  effects: {
    getMenuData: Effect;
    getMerchantsData: Effect;
  };
  reducers: {
    save: Reducer<MenuModelState>;
  };
}

// 一级菜单的判断  => 任意2级菜单其下存在查看则展示一级菜单
const firstMenu = (list = []) => {
  let flag = false;
  list.forEach(item => {
    if (item.children && item.children.length > 0) {
      item.children.forEach(i => {
        if (i.resourceCode.endsWith("_show")) {
          flag = true;
        }
      })
    }
  });
  return flag;
};

// 菜单的数据转化方法
const transformData = (data) => {
  return data.map(item => {
    item.path = item.resourceCode;
    item.name = item.resourceName;
    item.icon = getIcon(item.resourceIcon);
    item.hideInMenu = item.resourceType !== 0;
    // 如果属于一级菜单并且存在子节点
    if (item.resourceType === 0 && item.children && item.children.length > 0) {
      item.hideInMenu = false;
    }
    // 如果属于二级菜单并且存在子节点  其下没有查看权限，隐藏该二级菜单
    // if(item.resourceType === 0 && item.children && item.children.length > 0){
    //   const second = item.children.filter(i => i.resourceCode.endsWith("_show"));
    //   item.hideInMenu = second.length === 0;
    // }
    if (item.children && item.children.length > 0) {
      item.rounts = transformData(item.children);
    }
    return item;
  })
};


const MenuModel: MenuModelType = {
  namespace: 'menu',
  state: {
    menuData: [],
    dicData: [],
    permissions: [],
    userProfile: {},
    pwdStrategy: {},
    orgType: '',
    dataPermission: {},
    basicData: {
      menuData: [],
      logoUrl: '',
      thumbnailLogoUrl: ''
    },
    merchantsData: {},
  },
  effects: {
    *getMenuData({ payload, callback }, { call, put }) {
      const response = yield call(getMenuData);
      if (response.statusCode === "0") {
        const menu = response.data.resources ? response.data.resources : [];
        const profile = response.data.userProfile ? response.data.userProfile : {};
        if(profile.userMail){
          profile['userMail'] = decryptedData(profile.userMail, privateKey)
        }
        if(profile.userMobile){
          profile['userMobile'] = decryptedData(profile.userMobile, privateKey)
        }
        if(profile.userPhone){
          profile['userPhone'] = decryptedData(profile.userPhone, privateKey)
        }
        const dict = response.data.dictList ? response.data.dictList : [];
        const permissions = response.data.permissionCodes ? response.data.permissionCodes : [];
        const pwdStrategy = response.data.pwdStrategy ? response.data.pwdStrategy : {};
        const brandId = response?.data?.dataPermission?.BRAND || [];
        const basicData = {
          menuData: transformData(menu),
          logoUrl: response?.data?.logoUrl || '',
          thumbnailLogoUrl: response?.data?.thumbnailLogoUrl || '',
        }
        const orgType = response.data.orgType ? response.data.orgType : '';
        const dataPermission = response.data.dataPermission ? response.data.dataPermission : {}
        sessionStorage.setItem('tenantLogoUrl', response.data.logoUrl ? response.data.logoUrl : '');
        yield put({
          type: 'save',
          payload: { menuData: transformData(menu), dicData: dict, userProfile: profile, permissions: permissions, pwdStrategy: pwdStrategy, orgType: orgType, dataPermission: dataPermission, brandId },
        });
        sessionStorage.setItem('tenantLogoUrl', response.data.logoUrl ? response.data.logoUrl : '');
        sessionStorage.setItem('accountName', profile.accountName || '');
        if (callback) callback(basicData);
      }
    },
    *getMerchantsData({ payload, callback }, { call, put }){
      const response = yield call(getMerchantsData);
      yield put({type: 'save', payload:{merchantsData: response.data ?? {}}})
    }
  },
  reducers: {
    save(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
  },
};
export default MenuModel;
